﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FIFP.Common;
using FIFP.DashBoard.Model;
using System.Collections.ObjectModel;
using System.ComponentModel;
using FIFP.DashBoard.Helper;
using Telerik.Windows.Controls;
using System.Collections.Generic;
using Telerik.Windows.Controls.ScheduleView;
using FIFP.DashBoard.Converters;
using System.Collections;
using System.Linq;

namespace FIFP.DashBoard.ViewModel
{
    public class OptMngVM : ViewModelCore
    {
        #region Variables
        private List<FIFPAppointment> lsdActivities;
        private List<FIFPAppointment> activityList;
        private ObservableCollection<FIFPAppointment> linkedShutdownList;
        private ObservableCollection<FIFPAppointment> filteredLinkedShutdownList;
        public event EventHandler<CustomEventArgs<AppointmentGroup>> OnAppointmentDataCompleted;

        private List<FIFPAppointment> activityListWithSelectedUnit;
        private ObservableCollection<FIFPAppointment> filteredActivityListWithSelectedUnit;
        #endregion

        #region Properties

        private ObservableCollection<Unit> filteredLSDLocations;
        public ObservableCollection<Unit> FilteredLSDLocations
        {
            get { return filteredLSDLocations; }
            set { SetPropertyValue(() => FilteredLSDLocations, value, val => filteredLSDLocations = val); }
        }

        private List<Unit> linkedShutdownLocations;
        public List<Unit> LinkedShutdownLocations
        {
            get { return linkedShutdownLocations; }
            set { SetPropertyValue(() => LinkedShutdownLocations, value, val => linkedShutdownLocations = val); }
        }

        private Unit selectedLSDLocation;
        public Unit SelectedLSDLocation
        {
            get { return selectedLSDLocation; }
            set { SetPropertyValue(() => SelectedLSDLocation, value, val => selectedLSDLocation = val); }
        }

        public List<FIFPAppointment> LsdActivities
        {
            get { return lsdActivities; }
            set { SetPropertyValue(() => LsdActivities, value, val => lsdActivities = val); }
        }



        public ObservableCollection<FIFPAppointment> LinkedShutdownList
        {
            get { return linkedShutdownList; }
            set { SetPropertyValue(() => LinkedShutdownList, value, val => linkedShutdownList = val); }
        }

        public ObservableCollection<FIFPAppointment> FilteredLinkedShutdownList
        {
            get { return filteredLinkedShutdownList; }
            set { SetPropertyValue(() => FilteredLinkedShutdownList, value, val => filteredLinkedShutdownList = val); }
        }

        public List<FIFPAppointment> ActivityList
        {
            get { return activityList; }
            set { SetPropertyValue(() => ActivityList, value, val => activityList = val); }
        }


        private FIFPAppointment selectedActivity;
        public FIFPAppointment SelectedActivity
        {
            get { return selectedActivity; }
            set { SetPropertyValue(() => SelectedActivity, value, val => selectedActivity = val); }
        }

        private FIFPAppointment modifiedSelectedActivity;
        public FIFPAppointment ModifiedSelectedActivity
        {
            get { return modifiedSelectedActivity; }
            set { SetPropertyValue(() => ModifiedSelectedActivity, value, val => modifiedSelectedActivity = val); }
        }

        public List<FIFPAppointment> ActivityListWithSelectedUnit
        {
            get { return activityListWithSelectedUnit; }
            set { SetPropertyValue(() => ActivityListWithSelectedUnit, value, val => activityListWithSelectedUnit = val); }
        }

        public ObservableCollection<FIFPAppointment> FilteredActivityListWithSelectedUnit
        {
            get { return filteredActivityListWithSelectedUnit; }
            set { SetPropertyValue(() => FilteredActivityListWithSelectedUnit, value, val => filteredActivityListWithSelectedUnit = val); }
        }
        private ObservableCollection<FIFPAppointment> optimizedActivityList = new ObservableCollection<FIFPAppointment>();
        public ObservableCollection<FIFPAppointment> OptimizedActivityList
        {
            get { return optimizedActivityList; }
            set { SetPropertyValue(() => OptimizedActivityList, value, val => optimizedActivityList = val); }
        }


        private List<Unit> treeViewUnitList = new List<Unit>();
        public List<Unit> TreeViewUnitList
        {
            get { return treeViewUnitList; }
            set { SetPropertyValue(() => TreeViewUnitList, value, val => treeViewUnitList = val); }
        }

        private List<Unit> unitList = new List<Unit>();
        public List<Unit> UnitList
        {
            get { return unitList; }
            set { SetPropertyValue(() => UnitList, value, val => unitList = val); }
        }

        private Grid treeViewGrid;
        public Grid TreeViewGrid
        {
            get { return treeViewGrid; }
            set { SetPropertyValue(() => TreeViewGrid, value, val => treeViewGrid = val); }
        }
       
        #endregion

        #region Commands

        private ICommand _TreeviewSelectionChanged;
        public ICommand TreeviewSelectionChanged
        {
            get
            {
                return _TreeviewSelectionChanged ??
                        (_TreeviewSelectionChanged = new RelayCommand<TreeView>(UnitTreeviewSelectionChanged));
            }
        }

        private ICommand _ActivitySelectChanged;
        public ICommand ActivitySelectChanged
        {
            get
            {
                return _ActivitySelectChanged ??
                        (_ActivitySelectChanged = new RelayCommand<DataGrid>(ActivityDatagridSelectionChange));
            }
        }

        private ICommand _ModifiedActivitySelectChanged;
        public ICommand ModifiedActivitySelectChanged
        {
            get
            {
                return _ModifiedActivitySelectChanged ??
                        (_ModifiedActivitySelectChanged = new RelayCommand<DataGrid>(ModifiedActivityDatagridSelectionChange));
            }
        }



        private ICommand _LSDLocationSelectionChanged;
        public ICommand LSDLocationSelectionChanged
        {
            get
            {
                return _LSDLocationSelectionChanged ??
                        (_LSDLocationSelectionChanged = new RelayCommand<DataGrid>(LSDLocationGridSelectionChange));
            }
        }
        private ICommand _TreeviewGridLoaded;
        public ICommand TreeviewGridLoaded
        {
            get
            {
                return _TreeviewGridLoaded ??
                        (_TreeviewGridLoaded = new RelayCommand<Grid>(LoadTreeviewGrid));
            }
        }
        #endregion

        #region Constructor
        public OptMngVM()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                filteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
                ServiceLocator.Get<MainPageVM>().OnOptimizationClick += new EventHandler(OptMngVM_OnOptimizationClick);
            }
        }

        #endregion

        #region Get the original plans from Import UI while we click linked shutdown button from MainPage
        void OptMngVM_OnOptimizationClick(object sender, EventArgs e)
        {
            ServiceLocator.Get<FilterVM>().IsDivisionEnabled = false;
            LinkedShutdownLocations = new List<Unit>();
            ServiceLocator.Get<AppointmentVM>().RadScheduleViewDragDropBehavior = new OptimizationScheduleDragDropBehavior();
            ActivityList = ServiceLocator.Get<ImportVM>().ImportPlans;
            UnitList = ServiceLocator.Get<ImportVM>().UnitList;

            foreach (Unit unit in UnitList)
            {
                unit.UnitNameTextColor = (unit.FluidType == FIFPConstants.FLUIDTYPE_OIL) ? new SolidColorBrush(new Color() { R = 0xFF, G = 0x59, B = 0x59, A = 0xFF }) : (unit.FluidType == FIFPConstants.FLUIDTYPE_WATER) ? new SolidColorBrush(new Color() { R = 0x4B, G = 0xAC, B = 0xC6, A = 0xFF }) : (unit.FluidType == FIFPConstants.FLUIDTYPE_GAS) ? new SolidColorBrush(new Color() { R = 0x93, G = 0xA8, B = 0x2A, A = 0xFF }) : new SolidColorBrush(new Color() { R = 0x17, G = 0x36, B = 0x5D, A = 0xFF });
            }

            if (ActivityList != null && ActivityList.Count > 0)
            {
                foreach (FIFPAppointment activity in ActivityList)
                {
                    activity.LsdPlans.ForEach(s => { s.IsAppointmentDelete = false; });//We set to false that don't delete linked shutdown activity in Optimization page
                    if (activity.UnitType == FIFPConstants.UNITTYPE_RADIAL || activity.UnitType == FIFPConstants.UNITTYPE_TOWER || activity.UnitType == FIFPConstants.UNITTYPE_PIPELINE)
                    {
                        activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                    }                   
                    else if (activity.UnitType == FIFPConstants.UNITTYPE_WELL && activity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG)
                    {
                        //Temporary comment
                        //activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(l => l.UnitType == FIFPConstants.UNITTYPE_TOWER && l.IsLinkedShutdownPlan == true));
                    }
                    else if (activity.UnitType == FIFPConstants.UNITTYPE_COMBINED_TOWER)
                    {
                        activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>(activity.LsdPlans.Where(s => s.FluidType == s.CombinedTowerLSDType && s.IsLinkedShutdownPlan == true));
                    }
                    else if (activity.UnitType != FIFPConstants.UNITTYPE_WELL || activity.UnitType != FIFPConstants.UNITTYPE_STRING)
                    {
                        activity.FilteredLsdPlans = new ObservableCollection<FIFPAppointment>();
                    }
                    Unit unit = UnitList.Where(u => u.UnitName == activity.UnitName && u.UnitType == activity.UnitType).FirstOrDefault();
                    if (unit != null && unit.UnitType != FIFPConstants.UNITTYPE_STRING && unit.UnitType != FIFPConstants.UNITTYPE_WELL && !LinkedShutdownLocations.Contains(unit) && activity.FilteredLsdPlans.Count > 0)
                    {
                        LinkedShutdownLocations.Add(unit);
                    }
                }

                List<FIFPAppointment> listForScheduleView = new List<FIFPAppointment>();
                if (SelectedActivity != null)
                    listForScheduleView.Add(SelectedActivity);
                if (FilteredLinkedShutdownList != null && FilteredLinkedShutdownList.Count > 0)
                    listForScheduleView.AddRange(FilteredLinkedShutdownList);
                FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>(listForScheduleView);
                LoadTimelineView(listForScheduleView);
            }
            FilteredLSDLocations = new ObservableCollection<Unit>(LinkedShutdownLocations);
        }
        #endregion

        #region Treeview selection changed event
        private void UnitTreeviewSelectionChanged(TreeView treeView)
        {

            FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>();
            Unit unit = treeView.SelectedItem as Unit;
            if (unit != null)
            {
                string selectedItem = Convert.ToString(unit.UnitName);
                if (!string.IsNullOrEmpty(selectedItem))
                {
                    ActivityListWithSelectedUnit = (from item in ActivityList
                                                    where item.UnitName == selectedItem
                                                    select item).ToList<FIFPAppointment>();
                }
            }
        }
        #endregion

        #region LoadTimelineView
        private void LoadTimelineView(List<FIFPAppointment> plans)
        {
            AppointmentGroup appointmentGroup = new AppointmentGroup();
            List<ResourceType> lstResources = new List<ResourceType>();
            List<Resource> unitList = new List<Resource>();
            ResourceType unitType = new ResourceType("Unit");
            unitType.DisplayName = "Unit";
            unitType.Name = "Unit";

            foreach (FIFPAppointment appointment in plans)
            {
                Resource resource = new Resource() { ResourceName = appointment.UnitName, DisplayName = appointment.UnitName, ResourceType = unitType.Name };
                if (!unitList.Contains(resource))
                    unitList.Add(resource);
                appointment.Resources.Add(resource);
            }

            appointmentGroup.Appointments = new List<FIFPAppointment>(plans);
            unitType.Resources.AddRange(unitList);
            lstResources.Add(unitType);


            appointmentGroup.ResourceTypes = lstResources;
            appointmentGroup.UnitList = unitList;

            if (OnAppointmentDataCompleted != null)
                OnAppointmentDataCompleted(this, new CustomEventArgs<AppointmentGroup>(appointmentGroup));

        }
        #endregion

        #region ActivityDatagridSelectionChange
        private void ActivityDatagridSelectionChange(DataGrid activityGrid)
        {
            FIFPAppointment activity = (FIFPAppointment)activityGrid.SelectedItem;
            if (activity != null)
            {


                activity.Category = new Category("Oil", new SolidColorBrush(new Color() { R = 0x00, G = 0xFF, B = 0x00, A = 0xFF }));
                SelectedActivity = activity;
            }
        }
        #endregion

        #region Modified datagrid change
        private void ModifiedActivityDatagridSelectionChange(DataGrid activityGrid)
        {
            FIFPAppointment activity = (FIFPAppointment)activityGrid.SelectedItem;
            if (activity != null)
            {


                ModifiedSelectedActivity = activity;
            }
        }

        #endregion

        #region Location datagrid selection changed
        private void LSDLocationGridSelectionChange(DataGrid locationGrid)
        {
            ServiceLocator.Get<FilterVM>().SelectedDivision = ServiceLocator.Get<FilterVM>().DivisionList[0];
            if (locationGrid != null && locationGrid.SelectedItem != null)
            {
                TreeViewGrid.Children.Clear();
                SelectedLSDLocation = locationGrid.SelectedItem as Unit;
                if (SelectedLSDLocation != null)
                {
                    ServiceLocator.Get<FilterVM>().IsDivisionEnabled = true;

                    if (SelectedLSDLocation.FluidType == FIFPConstants.FLUIDTYPE_COMBINED)
                        ServiceLocator.Get<FilterVM>().IsCombinedTowerChecked = true;
                    else
                        ServiceLocator.Get<FilterVM>().IsCombinedTowerChecked = false;

                    LoadTreeView(SelectedLSDLocation);

                    ActivityListWithSelectedUnit = (from item in ActivityList
                                                    where item.UnitName == SelectedLSDLocation.UnitName
                                                    select item).ToList<FIFPAppointment>();


                    FilteredActivityListWithSelectedUnit = new ObservableCollection<FIFPAppointment>(ActivityListWithSelectedUnit);
                    List<FIFPAppointment> lsdPlans = new List<FIFPAppointment>();

                    if (SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_TOWER)
                    {

                        List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == SelectedLSDLocation.UnitID).ToList<Unit>();
                        lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
                        List<int> childUnits = lstChildUnits.Select(p => p.UnitID).ToList<int>();

                        //select activities                                                             
                        foreach (FIFPAppointment appointment in ActivityListWithSelectedUnit)
                        {
                            appointment.IsSelectedLocationActivityLock = true;
                            lsdPlans.Add(appointment);
                            //lsdPlans.AddRange(appointment.FilteredLsdPlans);
                        }

                        foreach (Unit unitItem in lstChildUnits)
                        {
                            List<FIFPAppointment> childActivityList = ActivityList.Where(s => s.UnitID == unitItem.UnitID).ToList<FIFPAppointment>();
                            if (childActivityList != null && childActivityList.Count > 0)
                            {
                                lsdPlans.AddRange(childActivityList);
                                foreach (FIFPAppointment appoinment in ActivityListWithSelectedUnit)
                                {
                                    lsdPlans.AddRange(appoinment.LsdPlans.Where(s => s.UnitType == unitItem.UnitType && s.UnitID == unitItem.UnitID).ToList<FIFPAppointment>());
                                }
                            }
                        }
                        foreach (FIFPAppointment appointment in ActivityListWithSelectedUnit)
                        {
                            lsdPlans.AddRange(appointment.FilteredLsdPlans);
                        }
                        
                    }
                    else
                    {
                        List<int> linkedSDUnits = new List<int>();
                        foreach (FIFPAppointment appointment in ActivityListWithSelectedUnit)
                        {
                            appointment.IsSelectedLocationActivityLock = true;
                            lsdPlans.Add(appointment);
                            lsdPlans.AddRange(appointment.FilteredLsdPlans);
                            if (linkedSDUnits.Count == 0)
                                linkedSDUnits = appointment.FilteredLsdPlans.Select(s => s.UnitID).ToList<int>();
                        }
                        if (linkedSDUnits.Count > 0)
                            lsdPlans.AddRange(from activity in ActivityList
                                              where linkedSDUnits.Any(s => s.Equals(activity.UnitID))
                                              select activity);
                    }
                    LinkedShutdownList = FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>(lsdPlans);


                    LoadTimelineView(lsdPlans);
                }

            }
        }
        #endregion

        #region LoadTreeviewGrid
        private void LoadTreeviewGrid(Grid grdTreeView)
        {
            TreeViewGrid = grdTreeView;
        }
        #endregion

        #region LoadTreeView
        private void LoadTreeView(Unit selectedUnit)
        {
            if (selectedUnit != null)
            {
                TreeView treeView = new TreeView();
                treeView.Style = Application.Current.Resources["TreeViewStyleSMUR"] as Style;
                //treeView.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(treeView_SelectedItemChanged);
                TreeViewItem rootItem = new TreeViewItem();

                rootItem.Header = selectedUnit.UnitName;
                rootItem.Tag = selectedUnit;
                rootItem.Foreground = selectedUnit.UnitNameTextColor;
                rootItem.IsExpanded = true;
                rootItem.Expanded += new RoutedEventHandler(treeViewItem_Expanded);
                rootItem.Collapsed += new RoutedEventHandler(treeViewItem_Collapsed);
                treeView.Items.Add(rootItem);
                TreeViewGrid.Children.Add(treeView);
                if (selectedUnit.UnitType == FIFPConstants.UNITTYPE_TOWER)
                    GeUnitNameList(new List<Unit>() { selectedUnit }, rootItem, true);
                else
                    GeUnitNameList(selectedUnit.ChildUnitList, rootItem, false);
            }
        }

        void treeViewItem_Collapsed(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = sender as TreeViewItem;
            if (item != null && item.Tag != null)
            {
                Unit unit = item.Tag as Unit;
                if (unit != null)
                {
                    List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == unit.UnitID).ToList<Unit>();
                    lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
                    List<int> childUnits = lstChildUnits.Select(p => p.UnitID).ToList<int>();
                    List<FIFPAppointment> lstSelectedAppointments = (from activity in ActivityList
                                                                     where childUnits.Any(s => s.Equals(activity.UnitID))
                                                                     select activity).ToList<FIFPAppointment>();
                    foreach (FIFPAppointment appoinment in ActivityListWithSelectedUnit)
                    {
                        lstSelectedAppointments.AddRange(appoinment.LsdPlans.Where(s => (s.UnitType == FIFPConstants.UNITTYPE_PIPELINE || s.UnitType == FIFPConstants.UNITTYPE_WELL || s.UnitType == FIFPConstants.UNITTYPE_STRING) && childUnits.Any(p => p.Equals(s.UnitID))).ToList<FIFPAppointment>());
                    }
                    FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>(FilteredLinkedShutdownList.Except(lstSelectedAppointments));
                    LoadTimelineView(new List<FIFPAppointment>(FilteredLinkedShutdownList));
                }
            }
        }

        void treeViewItem_Expanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = sender as TreeViewItem;
            if (item != null && item.Tag != null)
            {
                Unit unit = item.Tag as Unit;
                if (unit != null)
                {
                    FIFPAppointment appointment = FilteredLinkedShutdownList.Where(s => s.UnitID == unit.UnitID).FirstOrDefault();
                    int index = FilteredLinkedShutdownList.IndexOf(appointment);

                    List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == unit.UnitID).ToList<Unit>();
                    lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
                    List<int> childUnits = lstChildUnits.Select(p => p.UnitID).ToList<int>();

                    //select activities                                                             
                    List<FIFPAppointment> lstSelectedAppointments = new List<FIFPAppointment>();
                    foreach (Unit unitItem in lstChildUnits)
                    {
                        List<FIFPAppointment> childActivityList = ActivityList.Where(s => s.UnitID == unitItem.UnitID).ToList<FIFPAppointment>();
                        if (childActivityList != null && childActivityList.Count > 0)
                        {
                            lstSelectedAppointments.AddRange(childActivityList);
                            foreach (FIFPAppointment appoinment in ActivityListWithSelectedUnit)
                            {
                                lstSelectedAppointments.AddRange(appoinment.LsdPlans.Where(s => s.UnitType == unitItem.UnitType && s.UnitID == unitItem.UnitID).ToList<FIFPAppointment>());
                            }
                        }
                    }

                    List<FIFPAppointment> filterdAppointments = new List<FIFPAppointment>(FilteredLinkedShutdownList);
                    filterdAppointments.InsertRange(index + 1, lstSelectedAppointments);
                    FilteredLinkedShutdownList = new ObservableCollection<FIFPAppointment>(filterdAppointments);
                    LoadTimelineView(new List<FIFPAppointment>(FilteredLinkedShutdownList));
                }
            }
        }

        void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {

        }
        #endregion

        #region GetUnitNameListByTower
        private void GetUnitNameListByTower(List<Unit> lstUnits, Unit rootItem)
        {
            foreach (Unit unit in lstUnits)
            {
                if (unit.UnitType == FIFPConstants.UNITTYPE_TOWER)
                {
                    rootItem.TowerUnitList = UnitList.Where(p => p.ParentUnitID == unit.UnitID).ToList();
                }
                GetUnitNameListByTower(unit.ChildUnitList, rootItem);
            }
        }
        #endregion

        #region Get Treeview UnitList
        private void GeUnitNameList(List<Unit> lstUnits, TreeViewItem rootItem, bool bInitial)
        {
            foreach (Unit unit in lstUnits)
            {
                if (unit.UnitType == FIFPConstants.UNITTYPE_TOWER)
                {
                    TreeViewItem towerNode = new TreeViewItem();
                    towerNode.Expanded += new RoutedEventHandler(treeViewItem_Expanded);
                    towerNode.Collapsed += new RoutedEventHandler(treeViewItem_Collapsed);
                    if (bInitial)
                    {
                        if (lstUnits != null && lstUnits[0] != null && lstUnits[0].ChildUnitList != null && lstUnits[0].ChildUnitList.Count > 0)
                        {
                            foreach (Unit childUnit in lstUnits[0].ChildUnitList)
                            {
                                if (childUnit.UnitType != FIFPConstants.UNITTYPE_TOWER)
                                {
                                    TreeViewItem node = new TreeViewItem();//Detach expand and collapse event for Well
                                    //node.Expanded += new RoutedEventHandler(treeViewItem_Expanded);
                                    //node.Collapsed += new RoutedEventHandler(treeViewItem_Collapsed);
                                    node.Header = childUnit.UnitName;
                                    node.Tag = childUnit;
                                    node.Foreground = childUnit.UnitNameTextColor;
                                    node.IsExpanded = true;
                                    rootItem.Items.Add(node);
                                    if (childUnit.UnitType == FIFPConstants.UNITTYPE_WELL)
                                    {
                                        foreach (Unit stringUnit in childUnit.ChildUnitList)
                                        {
                                            TreeViewItem childNode = new TreeViewItem(); //Detach expand and collapse event for Well
                                            //childNode.Expanded += new RoutedEventHandler(treeViewItem_Expanded);
                                            //childNode.Collapsed += new RoutedEventHandler(treeViewItem_Collapsed);
                                            childNode.Header = stringUnit.UnitName;
                                            childNode.Tag = stringUnit;
                                            childNode.Foreground = stringUnit.UnitNameTextColor;
                                            childNode.IsExpanded = false;
                                            node.Items.Add(childNode);
                                        }
                                    }
                                }
                            }
                        }
                        bInitial = false;
                    }
                    else
                    {
                        towerNode.Header = unit.UnitName;
                        towerNode.Tag = unit;
                        towerNode.Foreground = unit.UnitNameTextColor;
                        towerNode.IsExpanded = false;
                        rootItem.Items.Add(towerNode);
                    }
                    foreach (Unit childUnit in unit.ChildUnitList)
                    {
                        TreeViewItem node = new TreeViewItem();//Detach expand and collapse event for Well
                        //node.Expanded += new RoutedEventHandler(treeViewItem_Expanded);
                        //node.Collapsed += new RoutedEventHandler(treeViewItem_Collapsed);
                        node.Header = childUnit.UnitName;
                        node.Tag = childUnit;
                        node.Foreground = childUnit.UnitNameTextColor;
                        node.IsExpanded = true;
                        if (childUnit.UnitType == FIFPConstants.UNITTYPE_WELL)
                        {
                            foreach (Unit stringUnit in childUnit.ChildUnitList)
                            {
                                TreeViewItem childNode = new TreeViewItem();//Detach expand and collapse event for Well
                                //childNode.Expanded += new RoutedEventHandler(treeViewItem_Expanded);
                                //childNode.Collapsed += new RoutedEventHandler(treeViewItem_Collapsed);
                                childNode.Header = stringUnit.UnitName;
                                childNode.Tag = stringUnit;
                                childNode.Foreground = stringUnit.UnitNameTextColor;
                                childNode.IsExpanded = false;
                                node.Items.Add(childNode);
                            }
                        }
                        towerNode.Items.Add(node);
                    }
                }
                GeUnitNameList(unit.ChildUnitList, rootItem, bInitial);
            }
        }
        #endregion

    }
}
